package com.fafa.pos.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.SystemClock;
import android.util.Log;
import com.pax.api.PrintException;
import com.pax.api.PrintManager;
import com.pax.cocoa.tools.Convert;
import com.pax.cocoa.tools.entity.EFontAlign;
import com.pax.cocoa.tools.entity.PrintPage;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by zenglv on 2017/11/8.
 */
public class PrintTool {

    private Context context;
    private static PrintTool printTool;
    public PrintTool(Context context){
        this.context=context;
    }

    public static PrintTool getInstance(Context context){
        if(printTool == null){
            synchronized (PrintTool.class){
                if(printTool == null){
                    printTool = new PrintTool(context);
                }
            }
        }
        return printTool;
    }

    public void print(PrintPage page){
        finishPrint(page);
    }


    public void selfPrint() {

        PrintPage page = new PrintPage();

        // 图片
//        page.addLine().addUnit(getImageFromAssetsFile("ic_pax.jpg"), EFontAlign.CENTER);// 参数1：bitmap; 参数2 位置(CENTER 居中, LEFT 靠左, RIGHT 靠右)
        // 商户名称
        page.addLine().addUnit("商户名称：张三", 20, EFontAlign.LEFT);// 参数1：text; 参数2 字号大小; 参数3 位置(CENTER 居中, LEFT 靠左, RIGHT 靠右)
        // 订单号
        page.addLine().addUnit("1234567890456712345678904567", 20);
        // 版本信息
        page.addLine().addUnit("PAX-A920 spos_pos_pa_add V1.0.1", 18, EFontAlign.CENTER);
        // 换行
        page.addLine().addUnit("\n\n\n\n", 20);// 参数1：text; 参数2 字号大小;
        finishPrint(page);
    }

    private void finishPrint( PrintPage page){
        try {
        Bitmap bitmap = Convert.printPageToBitmap(context, page, 384);
        PrintManager.getInstance().prnBitmap(bitmap);
        PrintManager.getInstance().prnStart();
        while (true) {
            int status = PrintManager.getInstance().prnStatus();
            if (status != 0x01)
                break;
            SystemClock.sleep(100);
        }
        PrintManager.getInstance().prnInit();
        page.clear();
        bitmap.recycle();
    } catch (PrintException e) {
              int error = 0;
        if (e.exceptionCode <= 0x09) {
        	 Log.i("TAG", "打印失败");
        }
    }

}

    private Bitmap getImageFromAssetsFile(String fileName) {
        Bitmap image = null;
        AssetManager am = context.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

}
